package com.chenjun.web.interceptor;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.chenjun.common.Constant;
import com.chenjun.core.dao.generator.entity.SysLog;
import com.chenjun.core.dao.generator.entity.SysUser;
import com.chenjun.core.service.sys.SysLogService;
import com.chenjun.core.service.sys.SysResourceService;
import com.ibm.icu.util.Calendar;

/**
 * 
 * @Description: 系统操作日志的拦截器
 * @author yanjinyin
 * @date 2017年7月23日 下午4:44:55
 */
public class LoggerInterceptor extends HandlerInterceptorAdapter {
	
	private static final Logger logger = Logger.getLogger(LoggerInterceptor.class);
	
	@Autowired
	private SysLogService	sysLogService;
	
	@Autowired
	private SysResourceService	sysResourceService;
	
	/**
	 * 不记录日志的请求集合
	 */
	private static final String[] NOT_INCLUDED = {
		".js",".css",".png",".jpg",".gif","webserivce",".map",".woff","/getSliderMenu","/404.html","/500.html"
	};
	
	/**
	 * 	CRUD集合
	 * 	/search
	 *	/edit
	 *	/delete/
	 *	/get/
	 */
	private static final Map<String,String> CRUD_INCLUDED = new LinkedHashMap<String, String>(4){{
		put("/search","搜索");
		put("/edit","编辑");
		put("/add","新增");
		put("/delete","删除");
		put("/get","获取");
		put("/create","新增");
		put("/update","更新");
		put("/init","初始化");
	}};
	
	private static final String  DEFAULT_LIST = "/list.html";
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		String str = request.getServletPath();
		
		if(null!=str&&
				(str.indexOf(NOT_INCLUDED[0])==-1
				&&str.indexOf(NOT_INCLUDED[1])==-1
				&&str.indexOf(NOT_INCLUDED[2])==-1
				&&str.indexOf(NOT_INCLUDED[3])==-1
				&&str.indexOf(NOT_INCLUDED[4])==-1
				&&str.indexOf(NOT_INCLUDED[5])==-1
				&&str.indexOf(NOT_INCLUDED[6])==-1
				&&str.indexOf(NOT_INCLUDED[7])==-1
				&&str.indexOf(NOT_INCLUDED[8])==-1
				&&str.indexOf(NOT_INCLUDED[9])==-1)){
			SysLog log = new SysLog();
			log.setUrl(str);
			log.setMethods(sysResourceService.getResourceNameByUrl(getPrefixUrl(str))+getUrlName(str));
			
			LoggerRequestWrapper lrw = new LoggerRequestWrapper(request);
			log.setParams(lrw.getBody());
			
			log.setCreatedTime(Calendar.getInstance().getTime());
	        SysUser user = (SysUser) request.getSession().getAttribute(Constant.Session.USER.toString());
	        if(null!=user){
	        	log.setUserId(user.getId());
				log.setUserName(user.getUserName());
//				sysLogService.create(log);
	        }
		}
		
		return super.preHandle(request, response, handler);
	}
	
	private static String getUrlName(String url){
		if(StringUtils.isNoneBlank(url)){
			for(Iterator<String> iter = CRUD_INCLUDED.keySet().iterator();iter.hasNext();){
				String key = iter.next();
				if(url.indexOf(key)!=-1){
					return CRUD_INCLUDED.get(key);
				}
			}
		}
		return "";
	}
	
	/**
	 * 获取URL前缀
	 * @param url
	 * @return
	 * String
	 */
	private static String getPrefixUrl(String url){
		
		if(StringUtils.isNoneBlank(url)){
			for(Iterator<String> iter = CRUD_INCLUDED.keySet().iterator();iter.hasNext();){
				String key = iter.next();
				if(url.indexOf(key)!=-1){
					return url.substring(0, url.indexOf(key))+DEFAULT_LIST;
				}
			}
		}
		
		return url;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		super.afterCompletion(request, response, handler, ex);
	}
	
}
